package morenoapp.components.input;

import java.awt.Component;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.util.EventObject;
import javax.swing.JTable;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.TableCellEditor;
import morenoapp.components.input.InputAnswersTableModel.AnswerCellValue;
import morenoapp.model.data.MorenoAnswerItemFace;
import org.mb.listeners.IListenerManager;
import org.mb.listeners.RefListenerManager;

/**
 * Редактор выбора респондента для позиции в ответе на вопрос.
 *
 * @author dmitry.mamonov
 */
public class InputAnswersTableCellEditor implements TableCellEditor {
    IListenerManager<CellEditorListener> listenerManager = new RefListenerManager<CellEditorListener>(CellEditorListener.class);

    CellEditorListener listenerProxy = listenerManager.getProxy();

    InputSingleAnswerEditor editor = new InputSingleAnswerEditor();
    //InputAnswersTableModel tableModel;

    MorenoAnswerItemFace answerItemFace = null;

    public InputAnswersTableCellEditor(InputAnswersTableModel tableModel) {
        //this.tableModel = tableModel;
        editor.addFocusListener(new FocusAdapter() {
            @Override
            public void focusLost(FocusEvent e) {
              stopCellEditing();
            }
        });
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        answerItemFace = ((AnswerCellValue) value).getAnswerItem();
        editor.setSelectedRespondent(answerItemFace.getTarget());
        editor.setPassValue(answerItemFace.getAnswer().getRespondent());
        return editor;
    }

    @Override
    public Object getCellEditorValue() {
        if (editor.getSelectedRespondent() == answerItemFace.getAnswer().getRespondent()) {
            return null;
        } else {
            return editor.getSelectedRespondent();
        }
    }

    @Override
    public boolean isCellEditable(EventObject anEvent) {
        return true;
    }

    @Override
    public boolean shouldSelectCell(EventObject anEvent) {
        return true;
    }

    @Override
    public boolean stopCellEditing() {
        listenerProxy.editingStopped(new ChangeEvent(this));
        return true;
    }

    @Override
    public void cancelCellEditing() {
        editor.setSelectedRespondent(null);
        listenerProxy.editingCanceled(new ChangeEvent(this));
    }

    @Override
    public void addCellEditorListener(CellEditorListener l) {
        listenerManager.addListener(l);
    }

    @Override
    public void removeCellEditorListener(CellEditorListener l) {
        listenerManager.removeListener(l);
    }
}
